import {
  GestureState,
  lerp,
  clamp,
  Curves,
} from '../../utils/custom-route/util'

function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}

const {
  timing
} = wx.worklet

const {
  windowHeight
} = getApp().globalData;


const request = require('../../utils/request')

Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgList: [],
    dataList: []
  },
  onLoad() {
    this.devName = 'ME05A_BA82'
    this.devMac = 'A0:76:4E:AF:BA:82'
  },
  /* 选择文件,得到临时路径 */
  uploadImg() {
    var that = this;
    // chooseImage已停止维护，需使用chooseMedia选择上传
    wx.chooseMedia({
      count: 1, // 最多可以选择的文件个数
      mediaType: ['image'], // 文件类型
      sizeType: ['original'], // 是否压缩所选文件
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(result) {
        console.log(result);
        that.setData({
          imgList: result.tempFiles
        })
        // console.log(that.data.imgList);
        wx.getFileSystemManager().readFile({ // 读取本地文件内容
          filePath: result.tempFiles[0].tempFilePath,
          encoding: 'base64', // 编码格式
          success(res) {
            console.log(res.data); // 图片base64编码
          }
        })
      },
    })
  },

  getData() {
    request.post('/serialPort/getRefreshImg', {}).then(res => {
      console.log('aaaa', res);
      // res.splice(res.length - 1, 1);
      // console.log('bbbb', res);
      this.data.dataList = res
    })

    this.openBluetoothAdapter()
  },

  openBluetoothAdapter() {
    wx.openBluetoothAdapter({
      success: (res) => {
        this.startBluetoothDevicesDiscovery()
      },
      fail: (res) => {
        console.log('fail');
        if (res.errno === 1500102) {
          this.errorResult('蓝牙未开启')
        }
        if (res.errno === 103) {
          this.errorResult('蓝牙未授权')
        }
      }
    })
  },
  startBluetoothDevicesDiscovery() {
    if (this._discoveryStarted) {
      return
    }
    let _this = this
    this._discoveryStarted = true
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      success: (res) => {
        this.onBluetoothDeviceFound()
      },
      fail(e) {
        _this.errorResult('蓝牙启动失败')
        _this.stopOpt()
        console.log(e);
      }
    })
  },

  onBluetoothDeviceFound() {
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(device => {
        if (!device.name && !device.localName) {
          return
        }
        // this.filterDevDBm(device)
      })
    })
  },

  filterDevDBm(device) {
    const idx = inArray(this.data.devices, 'deviceId', device.deviceId)
    if (idx === -1) {
      this.data.devices[this.data.devices.length] = device
    } else {
      this.data.devices[idx] = device
    }
    if (this.filterDevValue) {
      if (JSON.stringify(this.data.devices) !==
        JSON.stringify(devNameFilter(this.data.devices, this.filterDevValue))) {
        this.data.devices = devNameFilter(this.data.devices, this.filterDevValue)
      }
    }
    if (this.clickIsTrue) {
      if (this.data.userByDevList.length > 0) {
        this.data.userByDevList.forEach(item => {
          this.data.devices = devMacFilter(this.data.devices, item.devMac)
        })
      }
    }
    if (this.theDbm && device.RSSI < this.theDbm) {
      for (let index = this.data.devices.length - 1; index > 0; index--) {
        const item = this.data.devices[index];
        if (item.RSSI < this.theDbm) {
          this.data.devices.splice(index, 1);
        }
      }
    }
    this.isScan = false
    this.setData({
      isScan: this.isScan,
      devices: this.data.devices
    })
  },

  sendData() {
    console.log(this.data.dataList);
    // let dataInfo = []
    // for (let i = 0; i < this.data.dataList.length; i++) {
    //   let arr = []
    //   for (let j = 0; j < this.data.dataList[i].length / 2; j++) {
    //     // console.log(1);
    //     arr.push(this.data.dataList[i].substring(j * 2, j * 2 + 2))
    //   }
    //   dataInfo.push(arr)
    // }
    // console.log(dataInfo);
    let dataInfo = this.data.dataList
    this.createBLEConnectionByUploader(dataInfo)
    console.log('1111 ', this.devName);
  },

  createBLEConnectionByUploader(dataInfo) {
    const deviceId = this.devMac
    const name = this.devName
    console.log(555);
    let _this = this
    wx.showToast({
      title: '正在创建连接',
      icon: 'loading',
      duration: 2000
    })
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        this.setData({
          connected: true,
          name,
          deviceId,
        })
        this.getBLEDeviceServicesByUploader(deviceId, dataInfo)
      },
      fail(e) {
        if (_this.data.createBLEErrorCount < 4) {
          wx.showToast({
            title: ('连接丢失重试' + _this.data.createBLEErrorCount),
            icon: 'loading',
            duration: 2000
          })
          setTimeout(function () {
            // 在这里写要延迟执行的代码
            _this.createBLEConnection(dataInfo)
            _this.data.createBLEErrorCount++
          }, 2000);
        } else {
          _this.errorResult('检查蓝牙状态')
          _this.data.createBLEErrorCount = 1
        }
      }
    })
  },

  createBLEConnection(dataInfo) {
    const deviceId = this.devMac
    const name = this.devName
    let _this = this
    wx.showToast({
      title: '正在创建连接',
      icon: 'loading',
      duration: 2000
    })
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        this.setData({
          connected: true,
          name,
          deviceId,
        })
        this.getBLEDeviceServicesByUploader(deviceId, dataInfo)
      },
      fail(e) {
        if (_this.data.createBLEErrorCount < 4) {
          wx.showToast({
            title: ('连接丢失重试' + _this.data.createBLEErrorCount),
            icon: 'loading',
            duration: 2000
          })
          setTimeout(function () {
            // 在这里写要延迟执行的代码
            _this.createBLEConnection(dataInfo)
            _this.data.createBLEErrorCount++
          }, 2000);
        } else {
          _this.errorResult('检查蓝牙状态')
          _this.data.createBLEErrorCount = 1
        }
      }
    })
  },

  getBLEDeviceServicesByUploader(deviceId, dataInfo) {
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            this.getBLEDeviceCharacteristicsByUploader(deviceId, res.services[i].uuid, dataInfo)
            return
          }
        }
      }
    })
  },

  getBLEDeviceCharacteristicsByUploader(deviceId, serviceId, dataInfo) {
    wx.showToast({
      title: '正在写入数据',
      icon: 'loading',
      duration: 2000
    })
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        // dataInfo
        // 必须在这里的回调才能获取
        wx.onBLECharacteristicValueChange(function (characteristic) {
          console.log('characteristic');
          let str = ab2hex(characteristic.value)
          console.log(str);
        })

        wx.readBLECharacteristicValue({
          // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
          deviceId,
          // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
          serviceId,
          // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
          characteristicId: '0000FE50-0000-1000-8000-00805F9B34FB',
          success(res) {
            console.log('readBLECharacteristicValue:', res)
          }
        })
        // let item = dataInfo[0]
        // dataInfo = 
        // dataInfo.push(item)
        this.writeBLECharacteristicValueByUploader(dataInfo, 0)
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })
  },

  writeBLECharacteristicValueByUploader(dataInfo, index) {
    let item = dataInfo[index]
    if (item) {
      console.log('item', item);
      // 将数据转换
      let byteData = new Uint8Array(item);
      //  let byteData = new Uint8Array([0x51,0x02]);
      let buffer = new ArrayBuffer(byteData.length);
      let dataView = new DataView(buffer);
      for (let i = 0; i < byteData.length; i++) {
        dataView.setUint8(i, byteData[i]);
      }
      // 开始写入到设备
      let _this = this
      wx.writeBLECharacteristicValue({
        deviceId: _this.devMac,
        serviceId: '0000FEF0-0000-1000-8000-00805F9B34FB',
        characteristicId: '0000FEA0-0000-1000-8000-00805F9B34FB',
        value: buffer,
        success(res) {
          console.log('发送数据包成功！' + index + ' / ' + dataInfo.length, res);
          wx.readBLECharacteristicValue({
            // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
            deviceId: _this.devMac,
            // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
            serviceId: '0000FEF0-0000-1000-8000-00805F9B34FB',
            characteristicId: '0000FEA0-0000-1000-8000-00805F9B34FB',
            success(res) {
              console.log('readBLECharacteristicValue:', res)
            }
          })
          _this.writeBLECharacteristicValueByUploader(dataInfo, index += 1)
        },
        fail(res) {
          _this.errorResult('发送失败！')
          console.log('发送失败！');
          console.log(res);
          console.log(dataInfo);
          console.log(index);
          console.log(_this.devMac);
        }
      })
    } else {
      this.successResult('发送成功！')
      this.closeBLEConnection()
      console.log('发送成功');
    }
  },

  errorResult(errorInfo) {
    wx.showToast({
      title: errorInfo,
      icon: 'error',
      duration: 2000
    })
  },
  successResult(successInfo) {
    wx.showToast({
      title: successInfo,
      icon: 'success',
      duration: 2000
    })
  },

  closeBLEConnection() {
    wx.closeBLEConnection({
      deviceId: this.devMac
    })
  },

  listenInData() {
    console.log(this.devMac);
    wx.notifyBLECharacteristicValueChange({
      state: true, // 启用 notify 功能
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId: this.devMac,
      // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
      serviceId: '0000FEF0-0000-1000-8000-00805F9B34FB',
      characteristicId: '0000FFFF-0000-1000-8000-00805F9B34FB',
      success(res) {
        console.log('notifyBLECharacteristicValueChange succes0s', res)
      }
    })
    wx.onBLECharacteristicValueChange(function(res) {
      console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`)
      console.log(ab2hex(res.value))
    })
  }
})